package com.fhzheng.controller;

import com.fhzheng.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 通过url传参
 * |---get方式Url传参
 * |---@PathVariable 即：url/id/1994 形式
 * |---@RequestParam 即：url?username=zed形式
 * |---POST方式传参
 * |---@RequestParam
 * |---请求体中加入文本
 * 配置文件传参
 * <p>
 * post不能用浏览器直接访问
 * 这里用Postman测试：
 * 或是使用firefox的RESTclient扩展应用来测试；
 * 但个人感觉，postman要好用一点
 */

@RestController
public class HelloController {

    public static Logger log = LoggerFactory.getLogger(HelloController.class);

    @GetMapping("/hello/{name}")
    public String hello(@PathVariable("name") String name) {
        // 形参的name可以随意
        System.out.println("获取到的name是：" + name);
        return "hello " + name;
    }

    @GetMapping("/hello")
    public String hello(@RequestParam("name") String name, @RequestParam("age") Integer age) {
        System.out.println("获取到的 name 是：" + name);
        System.out.println("获取到的 age 是：" + age);
        return "hello " + name + "，您的年龄是" + age;
    }

    @GetMapping("/helloDefault")
    public String helloDefault(@RequestParam(value = "name", defaultValue = "小明") String name) {
        System.out.println("获取到的name是：" + name);
        return "hello " + name;
    }

    @PostMapping("/user")
    public String add(@RequestParam("name") String name, @RequestParam("age") Integer age) {
        log.info(name + "  " + age);
        return "name:" + name + "\nage:" + age;
    }

    @PostMapping("/PostString")
    public String postString(HttpServletRequest request) {
        ServletInputStream is = null;
        try {
            is = request.getInputStream();
            StringBuilder sb = new StringBuilder();
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = is.read(buf)) != -1) {
                sb.append(new String(buf, 0, len));
            }
            System.out.println(sb.toString());
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @PostMapping("/save")
    //@ResponseBody
    public Map<String, Object> save(@RequestBody User user) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("user", user);
        log.info(map.toString());
        return map;
    }

    @PostMapping("/user01")
    public String user(@RequestBody User user) {
        log.info(user.toString());
        return null;
    }

}